package com.plexpt.chatgptonlinejava.config;

import cn.hutool.core.text.CharSequenceUtil;
import org.redisson.Redisson;
import org.redisson.api.NameMapper;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;

public class NrRedis {
    public NrRedis() {
    }

    public static RedissonClient createClient(RedisProperties redisProperties) {
        return Redisson.create(buildConfig(redisProperties));
    }

    private static Config buildConfig(RedisProperties properties) {
        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer()
                .setAddress(properties.getAddress())
                .setDatabase(properties.getDb())
                .setKeepAlive(true)
                .setConnectionPoolSize(properties.getPool().getSize())
                .setConnectionMinimumIdleSize(properties.getPool().getMinIdle());
        final String baseKey = properties.baseKey;
        if (CharSequenceUtil.isNotBlank(baseKey)) {
            NameMapper nameMapper = new NameMapper() {
                public String map(String name) {
                    return baseKey + name;
                }

                public String unmap(String name) {
                    return CharSequenceUtil.removePrefix(name, baseKey);
                }
            };
            singleServerConfig.setNameMapper(nameMapper);
        }

        config.setCodec(new StringCodec());
        return config;
    }
}